package com.yunshang.ys;

import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
//import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.yunshang.ys.base.BaseActivity;
import com.yunshang.ys.ui.tab1.MainFragment0;
import com.yunshang.ys.ui.MainFragment1;
import com.yunshang.ys.ui.MainFragment2;
import com.yunshang.ys.ui.MainFragment3;
import com.yunshang.ys.ui.MainFragment4;
import com.yunshang.ys.utils.ComplexUtil;
import com.yunshang.ys.utils.FreeRadioGroup;
import com.yunshang.ys.utils.ScreenUtil;

import java.util.ArrayList;
import java.util.List;


public class MainActivity extends BaseActivity {

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == 3)
                listpopmenu = null;
            if (msg.what == 2)
                childpopmenu = null;
            if (msg.what == 1)
                popmenu = null;
        }
    };

//    ImageView iv;
//    ScanCodeImageUtil sss;
//
//    TextView tv;

//    RelativeLayout activity_main;

    FrameLayout flMainRG;

    private Fragment[] arrFragment;
    private RadioButton[] radioButtons;

    FreeRadioGroup freeradioGroup;
    private LinearLayout llmenu;

    TextView tvMenuMessage;
    ImageView ivMenuList;
    private PopupWindow popmenu;
    private PopupWindow childpopmenu;
    private View popview;
    private View childpopview;
    private TextView tv_addgroup;
    private View listpopview;
    private PopupWindow listpopmenu;
    private ListView lv_popmenu;
    private List<String> listdata;
    private BaseAdapter myAdapter;
    private RadioGroup rgMain;
    private int ph;
    private int indiheight;
    private boolean floatclickdis = true;   // 点float show
    private boolean outclickdis;
    private boolean popmenuishowing;
    private boolean btnclick;
    private boolean popmenuisshowing;
    private boolean popdis;
    private boolean msgbtnclick;
    private boolean listbtnclick;
    private boolean isinitfloat = true;
    private boolean outdismiss;
    private int popmenuint;
    private boolean floatbtnclick;
    private boolean runonce = true;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

//        activity_main = (RelativeLayout) findViewById(R.id.activity_main);
        flMainRG = (FrameLayout) findViewById(R.id.flMainRG);

        initstatusbar();


        inittabs();


//        initlistpop();
//        initchildpop();
//        initmenu();


        radioButtons[0].setChecked(true);


        initfloat();

//        iv = (ImageView) findViewById(R.id.iv);
//        tv = (TextView) findViewById(R.id.tv);
//
////        sss = new ScanCodeImageUtil(getApplicationContext());
//        sss = new ScanCodeImageUtil(this);
//        sss.netDownImage("http://pic.58pic.com/58pic/12/03/18/68w58PICjJP.jpg",
//                "",iv);

//        sss.getmBitmap();


//        tv.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                YSHttp.createApi(DownImageApi.class)
//                        .registe("","","","","","")
//                        .subscribeOn(Schedulers.io())
//                        .observeOn(AndroidSchedulers.mainThread())
//                        .subscribe(new YSSubscriber<String>() {
//                            @Override
//                            public void onSuccess(String t) {
//                                Toast.makeText(MainActivity.this, t, Toast.LENGTH_SHORT).show();
//                            }
//                            @Override
//                            public void onFail(String msg) {
//                                Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_SHORT).show();
//                            }
//                        });
//            }
//        });


    }


    private void initlistpop() {

//        listpopview = View.inflate(getApplicationContext(), R.layout.pop_list_menu, null);
        listpopview = LayoutInflater.from(getApplicationContext()).inflate(R.layout.pop_list_menu, null, false);


        int screenHeight = ScreenUtil.getScreenHeight(getApplicationContext());
        int screenWidth = ScreenUtil.getScreenWidth(getApplicationContext());
        int statusHeight = ScreenUtil.getStatusHeight(getApplicationContext());
        int y100 = getResources().getDimensionPixelSize(R.dimen.y200);
        int x150 = getResources().getDimensionPixelSize(R.dimen.x150);
//        LinearLayout llpoplist = (LinearLayout) listpopview.findViewById(R.id.ll_poplist);
//        llpoplist.setMinimumHeight(screenHeight - statusHeight - dimensionPixelSize);
//        ViewGroup.LayoutParams layoutParams = listpopview.getLayoutParams();
//        ViewGroup.LayoutParams layoutParams = llpoplist.getLayoutParams();
//        layoutParams.height = screenHeight - statusHeight - dimensionPixelSize;


//        arrFragment[0].getTabPagerIndicator();
//        MainFragment0 fragmentByTag = (MainFragment0) getSupportFragmentManager().findFragmentByTag("0");
//        int indiheight = fragmentByTag.getTabPagerIndicator();

//        int ph = screenHeight - statusHeight - indiheight - flMainRG.getHeight();
        int tabheight = flMainRG.getHeight();   // init = 0
        ph = screenHeight - statusHeight - flMainRG.getHeight();


        listpopmenu = new PopupWindow(listpopview,
                ViewGroup.LayoutParams.WRAP_CONTENT,
                ViewGroup.LayoutParams.WRAP_CONTENT, false);
//                ph,
//                ViewGroup.LayoutParams.WRAP_CONTENT, false);
        listpopmenu.setOutsideTouchable(true);
        listpopmenu.setBackgroundDrawable(new BitmapDrawable(getResources(), (Bitmap) null));
//        listpopmenu.setFocusable(true);
        listpopmenu.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                mHandler.sendEmptyMessageDelayed(3, 300);
//                if (listbtnclick)
//                    listpopmenu = null;
            }
        });
//        listpopmenu.setTouchInterceptor(new View.OnTouchListener() {
//            @Override
//            public boolean onTouch(View v, MotionEvent event) {
//                if (event.getAction() == MotionEvent.ACTION_DOWN)
//                    listbtnclick = ComplexUtil.inRangeOfView()
////                if (event.getAction() == MotionEvent.ACTION_OUTSIDE) {
////                    listpopmenu.dismiss();
////                    return true;
////                }
//                return false;
//            }
//        });


        initlistview(ph);


    }

    private void initlistview(int ph) {
        lv_popmenu = (ListView) listpopview.findViewById(R.id.lv_popmenu);
//        lv_popmenu.setLayoutParams(new LinearLayout.LayoutParams(
//                LinearLayout.LayoutParams.WRAP_CONTENT,
//                LinearLayout.LayoutParams.WRAP_CONTENT
//        ));
        listdata = new ArrayList<>();
        for (int i = 0; i < 30; i++)
            listdata.add("影视" + i);

        myAdapter = new BaseAdapter() {
            @Override
            public int getCount() {
                return listdata.size();
            }

            @Override
            public Object getItem(int position) {
                return listdata.get(position);
            }

            @Override
            public long getItemId(int position) {
                return position;
            }

            @Override
            public View getView(final int position, View convertView, ViewGroup parent) {
                ViewHolder holder = null;
                if (convertView == null) {
                    holder = new ViewHolder();
                    convertView = View.inflate(getApplicationContext(), R.layout.item_poplist, null);
                    convertView.setTag(holder);
                } else {
                    holder = (ViewHolder) convertView.getTag();
                }
                holder.tv = (TextView) convertView.findViewById(R.id.tv_listitem);
                holder.tv.setText(listdata.get(position));
                holder.tv.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Toast.makeText(MainActivity.this, listdata.get(position), Toast.LENGTH_SHORT).show();
//                        listpopmenu.dismiss();
//                        popmenu.dismiss();
                    }
                });
                return convertView;
            }

            class ViewHolder {
                TextView tv;
            }
        };
        lv_popmenu.setAdapter(myAdapter);


        // 神器代码
        int height1 = lv_popmenu.getHeight();
        lv_popmenu.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);
        listpopmenu.setWidth(lv_popmenu.getMeasuredWidth());
        int height2 = lv_popmenu.getHeight();
        int height = listpopmenu.getHeight();


//        if (indiheight == 0) {
        int tabheight = flMainRG.getHeight();
        MainFragment0 fragmentByTag = (MainFragment0) arrFragment[0];
        indiheight = fragmentByTag.getTabPagerIndicator();  // init = 0
//            ph = ph - indiheight - tabheight;
        ph = ph - indiheight;
//        }
        if (listpopmenu.getHeight() != ph) {
            int listchildheight = lv_popmenu.getMeasuredHeight();
            if (listchildheight * listdata.size() > ph)
                listpopmenu.setHeight(ph);
        }

//        listpopmenu.setHeight(lv_popmenu.getMeasuredHeight());
        // 神器代码
    }

    private void initchildpop() {
        childpopview = View.inflate(getApplicationContext(), R.layout.pop_child_menu, null);

        tv_addgroup = (TextView) childpopview.findViewById(R.id.tv_addgroup);
        tv_addgroup.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(MainActivity.this, "add group", Toast.LENGTH_SHORT).show();
//                childpopmenu.dismiss();
//                popmenu.dismiss();
            }
        });

        childpopmenu = new PopupWindow(childpopview, ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT, false);
//        childpopmenu = new PopupWindow((View) childpopview.getParent(), ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT, false);
        childpopmenu.setOutsideTouchable(true);
        childpopmenu.setBackgroundDrawable(new BitmapDrawable(getResources(), (Bitmap) null));
//        childpopmenu.setFocusable(true);
        childpopmenu.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                mHandler.sendEmptyMessageDelayed(2, 300);
//                if (msgbtnclick)
//                    childpopmenu = null;
            }
        });
//        childpopmenu.setTouchInterceptor(new View.OnTouchListener() {
//            @Override
//            public boolean onTouch(View v, MotionEvent event) {
//                if(event.getAction()==MotionEvent.ACTION_OUTSIDE){
//                    childpopmenu.dismiss();
//                    return true;
//                }
//                return false;
//            }
//        });
    }


    private void initmenu() {
//        View inflate = LayoutInflater.from(getApplicationContext()).inflate(R.layout.pop_menu, null);
        popview = View.inflate(getApplicationContext(), R.layout.pop_menu, null);
//        popview.setOnTouchListener(new View.OnTouchListener() {
//            @Override
//            public boolean onTouch(View v, MotionEvent event) {
//                if (v.getId() == R.id.tv_menu_messsage)
//                    msgbtnclick = true;
//                else msgbtnclick = false;
//                if (v.getId() == R.id.iv_menu_list)
//                    listbtnclick = true;
//                else listbtnclick = false;
//                return false;
//            }
//        });

//        popview.setOnTouchL
        llmenu = (LinearLayout) popview.findViewById(R.id.llmenu);

        tvMenuMessage = (TextView) popview.findViewById(R.id.tv_menu_messsage);
//        tvMenuMessage.setClickable(true);
//        tvMenuMessage.setOnTouchListener(new View.OnTouchListener() {
//            @Override
//            public boolean onTouch(View v, MotionEvent event) {
//                switch (event.getAction()) {
//                    case MotionEvent.ACTION_DOWN:
//                        msgbtnclick = true;
//                        break;
//                    case MotionEvent.ACTION_MOVE:
//                        msgbtnclick = false;
//                        break;
//                    case MotionEvent.ACTION_UP:
//                        if (msgbtnclick)
//                            if (childpopmenu != null) {
//                                childpopmenu.dismiss();
//                                childpopmenu = null;
//                            } else {
//                                initchildpop();
//                                childpopmenu.showAtLocation(getWindow().getDecorView(), Gravity.RIGHT, popview.getWidth(), 0);
//                            }
//                        break;
//                    default:
//                }
//                return false;
//            }
//        });
        tvMenuMessage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (childpopmenu != null) {
                    childpopmenu.dismiss();
                    childpopmenu = null;
                } else {
                    initchildpop();
                    childpopmenu.showAtLocation(getWindow().getDecorView(), Gravity.RIGHT, popview.getWidth(), 0);
                }

            }
        });

        ivMenuList = (ImageView) popview.findViewById(R.id.iv_menu_list);

//        ivMenuList.setClickable(true);
//        ivMenuList.setOnTouchListener(new View.OnTouchListener() {
//            @Override
//            public boolean onTouch(View v, MotionEvent event) {
//                switch (event.getAction()) {
//                    case MotionEvent.ACTION_DOWN:
//                        listbtnclick = true;
//                        if (indiheight == 0) {
//                            int tabheight = flMainRG.getHeight();
//                            MainFragment0 fragmentByTag = (MainFragment0) arrFragment[0];
//                            indiheight = fragmentByTag.getTabPagerIndicator();  // init = 0
//                            ph = ph - indiheight - tabheight;
//                        }
//                        if (listpopmenu.getHeight() != ph) {
//                            int listchildheight = lv_popmenu.getMeasuredHeight();
//                            if (listchildheight * listdata.size() > ph)
//                                listpopmenu.setHeight(ph);
//                        }
//                        break;
//                    case MotionEvent.ACTION_UP:
//                        if (listbtnclick)
//                            listpopmenu.showAtLocation(getWindow().getDecorView(),
//                                    Gravity.LEFT | Gravity.TOP, 0,
//                                    ScreenUtil.getStatusHeight(getApplicationContext()) + indiheight);
//                        break;
//                    default:
//                }
//                return false;
//            }
//        });

        ivMenuList.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (listpopmenu != null) {
                    listpopmenu.dismiss();
                    listpopmenu = null;
                } else {
                    initlistpop();
                    listpopmenu.showAtLocation(getWindow().getDecorView(),
                            Gravity.LEFT | Gravity.TOP, 0,
                            ScreenUtil.getStatusHeight(getApplicationContext()) + indiheight);
                }
            }
        });


        popmenu = new PopupWindow(popview, ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT, false);
        popmenu.setOutsideTouchable(true);
//        popmenu.
        popmenu.setBackgroundDrawable(new BitmapDrawable(getResources(), (Bitmap) null));
//        popmenu.setTouchInterceptor(new View.OnTouchListener() {
//            @Override
//            public boolean onTouch(View v, MotionEvent event) {
////                if (event.getAction() == MotionEvent.ACTION_DOWN) {
//                if (v.getId() == R.id.tv_menu_messsage)
//                    msgbtnclick = true;
//                else msgbtnclick = false;
//                if (v.getId() == R.id.iv_menu_list)
//                    listbtnclick = true;
//                else listbtnclick = false;
////                msgbtnclick = ComplexUtil.inRangeOfView(tvMenuMessage, event);
////                listbtnclick = ComplexUtil.inRangeOfView(ivMenuList, event);
////                }
////                if(event.getAction()==MotionEvent.ACTION_OUTSIDE){
////                    popmenu.dismiss();
////                    return true;
////                }
//                return false;
//            }
//        });
//        popmenu.setFocusable(true);


        popmenu.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                mHandler.sendEmptyMessageDelayed(1, 300);
            }
        });


    }

    private void initfloat() {

//        llmenu = (LinearLayout) findViewById(R.id.llmenu);


        freeradioGroup = (FreeRadioGroup) findViewById(R.id.floatgroup);
        ViewGroup.MarginLayoutParams lp = (ViewGroup.MarginLayoutParams) freeradioGroup.getLayoutParams();
//        ViewGroup.LayoutParams layoutParams = freeradioGroup.getLayoutParams();
//        layoutParams.height=300;
//        layoutParams.width=300;

//        popview.measure(View.MeasureSpec.AT_MOST, View.MeasureSpec.AT_MOST);
//
//        int width2 = popmenu.getWidth();
//        int height2 = popmenu.getHeight();
//        int width1 = freeradioGroup.getWidth();
//        int height1 = flMainRG.getHeight();
//        int width = popview.getWidth();
//        int height = popview.getHeight();
        lp.leftMargin = ScreenUtil.getScreenWidth(getApplicationContext()) -
                getResources().getDimensionPixelSize(R.dimen.x120);
        lp.topMargin = ScreenUtil.getScreenHeight(getApplicationContext()) -
                getResources().getDimensionPixelSize(R.dimen.y200);
//                height1;

//        freeradioGroup.setOnTouchListener(new View.OnTouchListener() {
//            @Override
//            public boolean onTouch(View v, MotionEvent event) {
//                switch (event.getAction()) {
//                    case MotionEvent.ACTION_DOWN:
//                        btnclick = true;
//                        break;
//                    case MotionEvent.ACTION_MOVE:
//                        break;
//                    case MotionEvent.ACTION_UP:
//                        if (btnclick) {
//                            popmenu.showAtLocation(getWindow().getDecorView(), Gravity.RIGHT, 0, 0);
//                        }
//                        break;
//                    default:
//                }
//                return false;
//            }
//        });

        // 给他个事件，不然不能touch
        freeradioGroup.setClickable(true);
        // touch 自己的 回调
        freeradioGroup.setOnMyTouch(new FreeRadioGroup.MyTouch() {
            @Override
            public void mydown() {
                btnclick = true;
            }

            @Override
            public void mymove() {
                btnclick = false;
            }

            @Override
            public void myup() {
                if (btnclick) {
                    if (popmenu != null) {
                        popmenu.dismiss();
                        popmenu = null;
                    } else {
                        initmenu();
                        popmenu.showAtLocation(getWindow().getDecorView(), Gravity.RIGHT, 0, 0);

                    }
                }
            }
        });


//        freeradioGroup.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
////                if (popmenu != null) {
////                    popmenu.dismiss();
////                    popmenu = null;
////                } else {
////                    initmenu();
////                    popmenu.showAtLocation(getWindow().getDecorView(), Gravity.RIGHT, 0, 0);
////                }
//            }
//        });
    }


    private void inittabs() {

        arrFragment = new Fragment[5];

        arrFragment[0] = new MainFragment0();
        arrFragment[1] = new MainFragment1();
        arrFragment[2] = new MainFragment2();
        arrFragment[3] = new MainFragment3();
        arrFragment[4] = new MainFragment4();
        radioButtons = new RadioButton[5];
        radioButtons[0] = (RadioButton) findViewById(R.id.rb_home);
        radioButtons[1] = (RadioButton) findViewById(R.id.rb_friend);
        radioButtons[2] = (RadioButton) findViewById(R.id.rb_job);
        radioButtons[3] = (RadioButton) findViewById(R.id.rb_activity);
        radioButtons[4] = (RadioButton) findViewById(R.id.rb_my);

        rgMain = (RadioGroup) findViewById(R.id.rb_main);
        rgMain.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                switch (checkedId) {
                    case R.id.rb_home:
//                        if (isinitfloat) {
//                            isinitfloat = false;
//                            initfloat();
//                        }
                        showFragmentOfPersonal(0);
                        break;
                    case R.id.rb_friend:
                        showFragmentOfPersonal(1);
                        break;
                    case R.id.rb_job:
                        showFragmentOfPersonal(2);
                        break;
                    case R.id.rb_activity:
                        showFragmentOfPersonal(3);
                        break;
                    case R.id.rb_my:
                        showFragmentOfPersonal(4);
                        break;
                }
            }
        });
    }

    //显示不同个人界面Fragment
    private void showFragmentOfPersonal(int index) {
        FragmentManager fragmentManager = getSupportFragmentManager();
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
//        fragmentTransaction.add(arrFragment[0], "0")
//                .add(arrFragment[0], "1")
//                .add(arrFragment[0], "2")
//                .add(arrFragment[0], "3")
//                .add(arrFragment[0], "4");
        fragmentTransaction.hide(arrFragment[0])
                .hide(arrFragment[1])
                .hide(arrFragment[2])
                .hide(arrFragment[3])
                .hide(arrFragment[4]);
        if (arrFragment[index].isAdded()) {
            fragmentTransaction.show(arrFragment[index]).commitAllowingStateLoss();
        } else {
            fragmentTransaction
                    .add(R.id.flMain, arrFragment[index])
                    .show(arrFragment[index])
                    .commitAllowingStateLoss();
        }
    }

//    @Override
//    public boolean onTouchEvent(MotionEvent event) {
////        popmenu.dismiss();
////        childpopmenu.dismiss();
////        listpopmenu.dismiss();
//        return super.onTouchEvent(event);
//    }


//    @Override
//    public boolean dispatchTouchEvent(MotionEvent ev) {
////        if (ev.getAction() == MotionEvent.ACTION_DOWN)
////            floatbtnclick = ComplexUtil.inRangeOfView(freeradioGroup, ev);
//        return super.dispatchTouchEvent(ev);
//    }
}
